const rob = nums => {
  let n = nums.length
  if (n === 0) return 0
  if (n === 1) return nums[0]
  if (n === 2) return Math.max(nums[0], nums[1])

  return Math.max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1))
}

const robRange = (nums, start, end) => {
  let sum1 = nums[start],
    sum2 = Math.max(nums[start], nums[start + 1])
  for (let i = start + 2; i <= end; i++) {
    const temp = Math.max(nums[i] + sum1, sum2)
    sum1 = sum2
    sum2 = temp
  }
  return sum2
}

console.log(rob([1, 2, 3, 1]));